﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json;

namespace ShelSystemViewer
{
	/// <summary>
	/// A wrapper around consuming the shell stream service
	/// </summary>
	internal class StreamClient
	{
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public IEnumerable<String> Connect(string host="127.0.0.1", int port = 8080)
		{
			var buffer = new byte[1024];
			var request = "GET / HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\n\r\n";
			var client = new System.Net.Sockets.TcpClient(host, port);
			using (var stream = client.GetStream())
			{
				var count = 0;
				var encoded = Encoding.ASCII.GetBytes(request);
				stream.Write(encoded, 0, encoded.Length);
				stream.Read(buffer, 0, buffer.Length); // dump the http headers
				while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
				{
					var result = Encoding.ASCII.GetString(buffer, 0, count);
					var message = result.Split('\n')[1];
                    // return raw string message since it could be a traumatic hit or a statistic
                    yield return message;
				}
			}
		}
	}
}
